package com.hhd.form.table;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hhd.base.utils.CommonUtils;
import com.hhd.form.entity.DesignFormFieldDefinition;
import com.hhd.form.entity.DesignFormViewDefinition;
import com.hhd.form.mapper.DesignFormMapper;
import com.hhd.form.service.IDesignFormDefinitionService;
import com.hhd.form.service.IDesignFormFieldDefinitionService;
import com.hhd.form.service.IDesignFormViewDefinitionService;
import com.hhd.form.service.IFormTableService;
import com.hhd.form.table.field.FormFieldBuilder;
import com.hhd.form.vo.FormDefinition;
import com.hhd.form.vo.SubFormDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AutoTableCreator {
    @Autowired
    DesignFormMapper formMapper;

    @Autowired
    IFormTableService formTableService;

    @Autowired
    FormTableBuilder formTableBuilder;

    @Autowired
    FormFieldBuilder formFieldBuilder;

    @Autowired
    IDesignFormDefinitionService formDefinitionService;

    @Autowired
    IDesignFormViewDefinitionService formViewDefinitionService;

    @Autowired
    IDesignFormFieldDefinitionService fieldDefinitionService;

    public synchronized void patchTable(FormDefinition fomDefinition) {
        createIds(fomDefinition);
        resolveDefaultValues(fomDefinition);
        buildFormTables(fomDefinition);
        buildFormFields(fomDefinition);
    }

    private void resolveDefaultValues(FormDefinition fomDefinition) {
        fomDefinition.setSort(0);
        List<SubFormDefinition> subForms = fomDefinition.getSubForms();
        if (!CommonUtils.isEmpty(subForms)) {
            int sort = 0;
            for (SubFormDefinition subForm : subForms) {
                subForm.setSort(++sort);
            }
        }
    }

    private void createIds(FormDefinition fomDefinition) {
        if(CommonUtils.isEmpty(fomDefinition.getId())) {
            fomDefinition.setId(IdWorker.getIdStr());
        }
        List<SubFormDefinition> subForms = fomDefinition.getSubForms();
        if (CommonUtils.isEmpty(subForms)) return ;
        for (SubFormDefinition subForm : subForms) {
            if (CommonUtils.isEmpty(subForm.getId())) {
                subForm.setId(IdWorker.getIdStr());
            }
        }
    }

    private void buildFormFields(FormDefinition fomDefinition) {
        formFieldBuilder.buildFormFields(fomDefinition);
    }

    private void buildFormTables(FormDefinition fomDefinition) {
        formTableBuilder.buildFormTables(fomDefinition);
    }
}
